package controllers

import (
	"github.com/revel/revel"
	// "wuhuaguo.com/whgv01/app/routes"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
	"wuhuaguo.com/whg01/app/models"
	"wuhuaguo.com/whg01/app/models/products"
	"wuhuaguo.com/whg01/app/utils"
)

type Product struct {
	Application
}

func (p Product) Preview(id int) revel.Result {
	item := models.GetItem(id)
	if item == nil {
		return p.RenderText("获取商品数据失败")
	}

	ir := item.ItemToRender()
	return p.Render(ir, item)
}

func (c Product) Detail(id int) revel.Result {
	//查询商品数据
	results, err := c.Txn.Select(models.Item{}, `select * from item where Id = ?`, id)
	if err != nil {
		panic(err)
	}
	if len(results) == 0 {
		revel.INFO.Println("%s item not exists", id)
		return nil
	}
	item := results[0].(*models.Item)
	ir := item.ItemToRender()

	revel.INFO.Println("%t", ir)

	return c.Render(ir, item)
}

func (p *Product) AddItem() revel.Result {
	return p.Render()
}

func (c *Product) UploadProduct() revel.Result {
	r := c.Request
	user := c.connected()
	fmt.Println("method:", r.Method) //获取请求的方法
	r.ParseMultipartForm(32 << 20)

	var name = r.FormValue("name")
	var intro = r.FormValue("intro")
	var spec = r.FormValue("spec")
	var num, err = strconv.Atoi(r.FormValue("num"))
	price, err := strconv.ParseFloat(r.FormValue("price"), 32)
	if err != nil {
		fmt.Println(err.Error())
		return c.RenderText("请检查价格，必须为数字")
	}
	if err != nil {
		fmt.Println(err.Error())
		return c.RenderText("请检查数量，必须为数字")
	}

	images := getImageFiles(r, strconv.Itoa(user.UserId))
	for _, img := range images {
		fmt.Println(img)
	}

	item := &models.Item{
		Name:       name,
		SallerId:   user.UserId,
		Price:      price,
		Intro:      intro,
		Spec:       spec,
		SmImage:    images[0],
		FirstImage: images[1],
		Images:     strings.Join(images[2:], ","),
		Num:        num,
	}
	if err != nil {
		fmt.Println(err.Error())
		return c.RenderText("提交商品信息入库失败，请联系管理员")
	}
	err = models.Dbm.Insert(item)
	if err != nil {
		revel.ERROR.Println(err.Error())
		return c.RenderText("提交商品信息入库失败，请联系管理员:\n" + err.Error())
	}
	fmt.Printf("item id %d\n", item.Id)
	//更新商品信息到列表中：
	models.CacheSetItem(item)
	//file
	return c.Redirect("/")
}

/**
获取form提交的五个图片，  放到数组中[小图、主图、副图1、副图2、副图3]， 如果没有就是是空
*/
func getImageFiles(r *revel.Request, userid string) []string {
	imges := [5]string{"main-sm-img", "main-img", "sub-main-img1", "sub-main-img2", "sub-main-img3"}
	var res []string

	for _, formname := range imges {
		file, handler, err := r.FormFile(formname)
		if err != nil {
			fmt.Println(err.Error())
			res = append(res, "")
			continue
		}
		defer file.Close()
		strs := strings.Split(handler.Filename, ".")
		sufix := ""
		imagename := ""
		if len(strs) >= 2 {
			img_static_name := utils.RandomString(userid, 16)
			sufix = strs[len(strs)-1]
			imagename = img_static_name + "." + sufix
			res = append(res, "/static/images/"+imagename)
		} else {
			res = append(res, "")
		}

		f, err := os.OpenFile("/data0/whg/static/images/"+imagename, os.O_WRONLY|os.O_CREATE, 0666) // 此处假设当前目录下已存在test目录

		if err != nil {
			fmt.Println(err.Error())
		}
		defer f.Close()
		io.Copy(f, file)

	}
	return res
}

/*
	获取商户所有的商品信息
*/
// 如果userid 不为空 则获取该用户的所有商品，  这是来自于管理员的请求
// 如果userid 为空， 则获取用户信息，这是来自于商家的请求

func (p *Product) GetItems(userid int) revel.Result {
	//
	if userid == 0 {
		user := p.connected()
		return p.RenderText(models.GetItemByUserid(user.UserId))
	} else {
		return p.RenderText(models.GetItemByUserid(userid))
	}

}

//审核通过 商品

func (p *Product) Approve(id int) revel.Result {
	products.UpdateItemStatus(id, 1)
	return p.RenderText("OK")
}
